<template>
  <div class="oe-enter-exam" v-loading="loading">
    <info-top @toggleCollapsed="toggleCollapsed" :userShow="false"></info-top>
    <div v-if="isUseCamera && takeTime > 0" style="line-height: 50px;text-align:center;">拍照倒计时{{ takeTime }}s</div>
    <div class="oe-exam-content">
      <h3 class="oe-exam-title">考试注意事项</h3>
      <div class="oe-content-lis">
        <div class="oe-content-label">考试时间：</div>
        <div class="oe-content-title">
          {{ startTime }}
          <span style="margin: 0px 10px;">——</span>
          {{ endTime }}
        </div>
      </div>
      <div class="oe-content-lis">
        <div class="oe-content-label">提前登录时长：</div>
        <div class="oe-content-title">
          <span style="color:#F56353;">{{ advanceTime }}</span
          >分钟
        </div>
      </div>
      <div class="oe-content-lis">
        <div class="oe-content-label">延迟登录时长：</div>
        <div class="oe-content-title">{{ extendTime }}分钟</div>
      </div>
      <div class="oe-content-lis">
        <div class="oe-content-label">提前交卷时长：</div>
        <div class="oe-content-title">{{ allowTime }}分钟</div>
      </div>
      <div class="oe-content-lis" v-if="changePaperCount > 0 || cameraChangeCount > 0">
        <div class="oe-content-label">考试规则：</div>
        <div class="oe-content-title">
          <span v-if="changePaperCount > 0">
            离开页面超过
            <span style="color:#F56353;">{{ changePaperCount }}</span
            >次，
            <span v-if="buckleScore > 0">
              每次扣
              <span style="color:#F56353;">{{ buckleScore }}</span
              >分 ;
            </span>
          </span>
          <span v-if="cameraChangeCount > 0">
            摄像头检测您离开
            <span style="color:#F56353;">{{ cameraChangeCount }}</span
            >次，
            <span v-if="cameraBuckleScore > 0">
              每次扣
              <span style="color:#F56353;">{{ cameraBuckleScore }}</span
              >分，
            </span>
          </span>
          将会自动提交请认真作答！
        </div>
      </div>
      <div class="oe-content-lis" v-if="monitorMobile">
        <div class="oe-content-label">技术人员电话：</div>
        <div class="oe-content-title">{{ monitorMobile }}</div>
      </div>
      <div class="oe-content-lis">
        <div class="oe-content-label">考试要求：</div>
        <div class="oe-content-title">{{ remark || '暂无考试要求' }}</div>
      </div>

      <div class="oe-content-lis" style="text-align: center;">
        <a-checkbox v-model="agree" @change="onChange">我已阅读并同意</a-checkbox>
      </div>
      <a-button :disabled="enterShow" type="primary" class="enter-exam-btn" size="large" @click="getExam">
        关闭并进入考试
        <span v-if="enterShow">({{ wait }})</span>
      </a-button>
    </div>
    <div class="oe-exam-camera" style="height: 240px;" v-show="isUseCamera && takeTime > 0">
      <video id="video" width="280" height="240" preload autoplay loop muted></video>
      <canvas id="canvas" width="280" height="240"></canvas>
      <canvas id="canvas2" width="320" height="240" style="display:none;"></canvas>
    </div>
    <a-modal v-model="remarkShow" title="考试要求" :closable="false" :maskClosable="false">
      <template slot="footer">
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">
          确定
        </a-button>
      </template>
      <p>{{remark}}</p>
      <div class="oe-content-lis" style="text-align: center;">
        <a-checkbox v-model="remarkIs">我已阅读</a-checkbox>
      </div>
    </a-modal>
  </div>
</template>

<script>
import infoTop from '@/components/info-top/index.vue';

import '@/lib/faceTrack/tracking-min.js';
import '@/lib/faceTrack/face-min.js';

export default {
  components: {
    infoTop
  },
  props: {
    Id: {
      type: String,
      default: ''
    }
  },
  destroyed() {
    clearInterval(this.canEnterTimeInterval);
    if (this.isUseCamera && this.isStart) {
      this.trackerTask.stop();
    }
    // 关闭摄像头
    if (this.isUseCamera && this.isStart) {
      this.mediaStreamTrack.srcObject && this.mediaStreamTrack.srcObject.getTracks()[0].stop();
      // this.trackerTask.closeCamera();
      // window.tracking.closeCamera();
      // console.log('执行了关闭');
    }
  },
  data() {
    return {
      collapsed: false,
      browser: '',
      startTime: '',
      endTime: '',
      advanceTime: 0,
      extendTime: 0,
      allowTime: 0,
      changePaperCount: '',
      buckleScore: '',
      cameraChangeCount: 0,
      cameraBuckleScore: '',
      remark: '',
      remarkShow: false,
      remarkIs: false,
      monitorMobile: '',
      wait: 5,
      enterShow: true,
      loading: false,
      mediaStreamTrack: '',
      isStart: false,
      canEnterDoTime: 10000,
      trackerTask: '',
      isUseCamera: true,
      takeTime: 5,
      workExamStuId: '',
      agree: false
    };
  },
  watch: {
    canEnterDoTime(val) {
      if (val <= 0) {
        clearInterval(this.canEnterTimeInterval);
      }
    }
  },
  mounted() {
    let ua = navigator.userAgent.toLowerCase();
    console.log('ua');
    console.log(ua);
    this.getPointInfo();
  },
  methods: {
    onChange() {
      console.log(this.agree);
    },
    // 监测摄像
    // 考试录像
    openCamera() {
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas = document.getElementById('canvas');
      var canvas2 = document.getElementById('canvas2');
      var context = canvas.getContext('2d');
      var tracker = new window.tracking.ObjectTracker('face');
      tracker.setInitialScale(4);
      tracker.setStepSize(2);
      tracker.setEdgesDensity(0.1);

      this.trackerTask = window.tracking.track('#video', tracker, { camera: true });
      // var isFirstStart = true;
      var that = this;
      tracker.on('track', function(event) {
        if (!that.isStart) {
          that.isStart = true;
        }
        context.clearRect(0, 0, canvas.width, canvas.height);
      });
    },
    getTake() {
      var that = this;
      setTimeout(() => {
        if (that.takeTime) {
          that.takeTime--;
          that.getTake();
        } else {
          that.snap();
          that.mediaStreamTrack.srcObject.getTracks()[0].stop();
          that.$message.success('已拍照');
        }
      }, 1000);
    },
    setTake() {
      const h = this.$createElement;
      var that = this;
      this.$info({
        title: '温馨提示',
        content: h('div', {}, [h('p', '该考试进入前需要拍照记录，请保证本人正面在摄像范围内。点击确定后5s拍照。')]),
        okText: '确定',
        onOk() {
          that.getTake();
        }
      });
    },
    snap() {
      var video = (this.mediaStreamTrack = document.getElementById('video'));
      var canvas2 = document.getElementById('canvas2');
      // //绘制canvas图形
      canvas2.getContext('2d').drawImage(video, 0, 0, 320, 240);
      // //把canvas图像转为img图片
      // // img.src = canvas2.toDataURL("image/png");
      // //执行上传
      this.saveExamPic(canvas2);
    },
    saveExamPic(canvas2) {
      let completeUrl = canvas2.toDataURL('image/png');
      let urlArr = completeUrl.split(',');
      let base64 = urlArr[1];

      let imgType = urlArr[0].replace('data:image/', '').replace(';base64', '');
      let file_system_url = localStorage.getItem('file_system_url');
      let postUrl = `${file_system_url}&extension=${imgType}&encode=base64`;
      this.$http.post(postUrl, base64).then((data) => {
        if (data) {
          this.randomSaveCameraPage(data.url);
          this.getSecond();
        }
      });
    },
    randomSaveCameraPage(url) {
      var browser = this.getBrowser();
      this.$http
        .post('/api/study/workexam/randomSaveCameraPage', {
          workExamStuId: this.workExamStuId, //学生作答Id
          workExamId: this.Id, //考试Id
          browser: browser, //浏览器类型
          url: url
        })
        .then((res) => {
          // if (res.code != 1) {
          //   this.$message.error(res.msg);
          // }
        });
    },
    toggleCollapsed(val) {
      this.collapsed = val;
    },
    getBrowser() {
      var ua = navigator.userAgent.toLocaleLowerCase();
      var Browser = null;
      if (ua.match(/msie/) != null || ua.match(/trident/) != null) {
        Browser = 'IE';
        browserVersion = ua.match(/msie ([\d.]+)/) != null ? ua.match(/msie ([\d.]+)/)[1] : ua.match(/rv:([\d.]+)/)[1];
        return 'IE';
      } else if (ua.match(/firefox/) != null) {
        Browser = '火狐';
        return 'FF';
      } else if (ua.match(/ubrowser/) != null) {
        Browser = 'UC';
        return 'UC';
      } else if (ua.match(/opera/) != null) {
        Browser = '欧朋';
        return 'OP';
      } else if (ua.match(/bidubrowser/) != null) {
        Browser = '百度';
        return 'baidu';
      } else if (ua.match(/metasr/) != null) {
        Browser = '搜狗';
        return 'SG';
      } else if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        Browser = 'QQ';
        return 'QQ';
      } else if (ua.match(/maxthon/) != null) {
        Browser = '遨游';
        return 'AY';
      } else if (ua.match(/chrome/) != null) {
        var is360 = this.mime('type', 'application/vnd.chromium.remoting-viewer');
        if (is360) {
          Browser = '360';
          return '360';
        } else {
          return 'Chrome';
        }
      } else if (ua.match(/safari/) != null) {
        Browser = 'Safari';
        return 'Safari';
      }
    },
    mime(option, value) {
      var mimeTypes = navigator.mimeTypes;
      for (var mt in mimeTypes) {
        if (mimeTypes[mt][option] == value) {
          return true;
        }
      }
      return false;
    },
    handleOk() {
      if (this.remarkIs) {
        this.remarkShow = false;
        // 是否监测摄像
        if (this.isUseCamera) {
          this.openCamera();
          this.setTake();
        } else {
          this.isStart = true;
          this.getSecond();
        }
      } else {
        this.$message.warning('请勾选我已阅读');
      }
    },
    getPointInfo() {
      this.loading = true;
      this.browser = this.getBrowser();
      this.$http
        .post('/api/study/workexam/getPointInfo', {
          examId: this.Id, //考试Id
          browser: this.browser, //作答浏览器
          sourceType: 1
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            this.startTime = res.startTime; //开始时间
            this.endTime = res.endTime; //结束时间
            this.advanceTime = res.advanceTime; //提前登录时长
            this.extendTime = res.extendTime; //延迟登录时长
            this.allowTime = res.allowTime; //提前交卷时长
            this.changePaperCount = res.changePaperCount; //切屏次数
            this.buckleScore = res.buckleScore; //切屏每次扣分
            this.remark = res.remark; //考试要求
            this.monitorMobile = res.monitorMobile;
            this.cameraChangeCount = res.cameraChangeCount;
            this.cameraBuckleScore = res.cameraBuckleScore;
            this.workExamStuId = res.workExamStuId; // 学生作答ID
            this.isUseCamera = res.isUseCamera; //是否开始摄像
            if (this.remark) {
              this.remarkShow = true;
            } else {
              // 是否监测摄像
              if (res.isUseCamera) {
                this.openCamera();
                this.setTake();
              } else {
                this.isStart = true;
                this.getSecond();
              }
            }
            
            this.canEnterDoTime = res.canEnterDoTime;
            if (this.canEnterDoTime > 0) {
              this.canEnterTimeInterval = setInterval(() => {
                this.canEnterDoTime--;
              }, 1000);
            }
          } else {
            var that = this;
            this.$error({
              title: '提示',
              content: res.msg,
              okText: '确定',
              onOk() {
                that.$router.go(-1);
              }
            });
          }
        });
    },
    getSecond() {
      let _this = this;
      let _wait = this.wait;
      if (this.wait == 0) {
        this.enterShow = false;
      } else {
        this.enterShow = true;
        this.wait--;
        setTimeout(function() {
          _this.getSecond();
        }, 1000);
      }
    },
    getExam() {
      if (this.canEnterDoTime > 0) {
        this.$message.warning('考试未开始，无法进入');
      } else if (!this.agree) {
        this.$message.warning('请勾选同意');
      } else {
        if (this.isStart) {
          this.$router.push({
            name: 'stuCurrentExam',
            params: {
              Id: this.Id, //考试Id
              routerGo: true
            }
          });
        } else {
          this.$message.warning('该考试需要摄像，监测您的设备无法摄像，请联系监考老师处理');
        }
      }
    }
  }
};
</script>
